﻿<%@ WebHandler Language="C#" Class="OfferPriceHandler" %>

using System;
using System.Web;
using System.Collections;
using System.Data;
using StarTech.DBUtility;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Web.DynamicData;


public class OfferPriceHandler : IHttpHandler
{
    AdoHelper ado = AdoHelper.CreateHelper(StarTech.Util.AppConfig.DBInstance);
    string memberId = "";
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        if (context.Request.Cookies["memberInfo"] != null && Common.CheckUser(context.Request.Cookies["memberInfo"].Value))
        {
            memberId = context.Request.Cookies["memberInfo"].Value.Split(new string[] { "$$" }, StringSplitOptions.RemoveEmptyEntries)[0];
            string flag = Common.NullToEmpty(context.Request["flag"]);

            string gid = Common.NullToEmpty(context.Request["gid"]);
            string mobile = Common.NullToEmpty(context.Request["mobile"]);
            string price = Common.NullToEmpty(context.Request["price"]);
            string jobType = Common.NullToEmpty(context.Request["jobType"]);

            string priceId = Common.NullToEmpty(context.Request["priceId"]);
            string confirm = Common.NullToEmpty(context.Request["confirm"]);

            switch (flag.ToLower())
            {
                case "list":
                    context.Response.Write(List(gid));
                    break;
                case "info":
                    context.Response.Write(GetGoodsInfo(gid));
                    break;
                case "add":
                    context.Response.Write(AddMemberPrice(gid, mobile, price, jobType));
                    break;
                case "delete":
                    context.Response.Write(Delete(priceId));
                    break;
                case "confirm":
                    context.Response.Write(AcceptOrder(priceId, confirm));
                    break;
            }
        }
        else
        {
            context.Response.Write("please login");
        }
    }

	private string List(string gid)
	{
		string json = "";

        string strSql = @"SELECT a.PriceId, a.MemberId, a.MemberPrice,a.MemberMobile, a.IsEmployerSelect, b.HeadImg,b.TrueName, b.LevelId,b.LevelName,a.IsLast,ISNULL(c.signCount,0) as signCount,ISNULL(a.jobDay-c.signCount,a.jobDay) as unsignCount 
                    FROM T_Goods_MemberPrice a 
                    left join T_Member_Info b on a.MemberId=b.MemberId 
                    left join (select MemberId,GoodsId,count(1) as signCount from T_Member_JobRecord group by MemberId,GoodsId) c on b.memberId=c.memberId and a.goodsId=c.goodsId 
                    left join T_Goods_Info d on a.goodsId=d.goodsId 
                    where a.IsLast=1 and a.GoodsId=@GoodsId order by a.EmployerSelectTime,a.CreateTime";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@GoodsId",gid)
        };
        json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p).Tables[0]);

        return json;
	}

    private string GetGoodsInfo(string gid)
    {
        string strSql = @"select AddressDetail, Specialty, Skill, SelfIntroduction,TrueName from t_member_info where memberid=@memberId;";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@memberId",memberId)
        };
        DataTable dt = ado.ExecuteSqlDataset(strSql, p).Tables[0];
        if (dt.Rows.Count > 0)
        {
            if (string.IsNullOrEmpty(Common.NullToEmpty(dt.Rows[0]["AddressDetail"])) ||
                string.IsNullOrEmpty(Common.NullToEmpty(dt.Rows[0]["Specialty"])) ||
                string.IsNullOrEmpty(Common.NullToEmpty(dt.Rows[0]["Skill"])) ||
                string.IsNullOrEmpty(Common.NullToEmpty(dt.Rows[0]["SelfIntroduction"])))
            {
                return "fill resume";
            }
            else
            {
                string json = "";

                strSql = @"select GoodsName,AddTime,JobType,SalePrice,isnull(b.offCount,0) as offCount from T_Goods_Info a
                    left join (select goodsid,count(1) as offCount from (select goodsid,memberid from T_Goods_MemberPrice group by goodsid,memberid) t group by GoodsId) b on a.GoodsId=b.GoodsId
                    where a.GoodsId=@gid";
                SqlParameter[] p2 = new SqlParameter[] {
                    new SqlParameter("@gid",gid)
                };
                json += JSONHelper.GetJSON(ado.ExecuteSqlDataset(strSql, p2).Tables[0]);

                return json;
            }
        }
        else
        {
            return "fill resume";
        }
    }

    private string AddMemberPrice(string gid, string mobile, string price, string jobType)
    {
        string strSql = @"select AddressDetail, Specialty, Skill, SelfIntroduction,TrueName from t_member_info where memberid=@memberId;";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@memberId",memberId)
        };
        DataTable dt = ado.ExecuteSqlDataset(strSql, p).Tables[0];
        if (dt.Rows.Count > 0)
        {
            if (string.IsNullOrEmpty(Common.NullToEmpty(dt.Rows[0]["AddressDetail"])) ||
                string.IsNullOrEmpty(Common.NullToEmpty(dt.Rows[0]["Specialty"])) ||
                string.IsNullOrEmpty(Common.NullToEmpty(dt.Rows[0]["Skill"])) ||
                string.IsNullOrEmpty(Common.NullToEmpty(dt.Rows[0]["SelfIntroduction"])))
            {
                return "fill resume";
            }
            else
            {
                strSql = @"select * from T_Goods_MemberPrice where memberid=@memberId and goodsId=@goodsId";
                SqlParameter[] p2 = new SqlParameter[] {
                    new SqlParameter("@memberId",memberId),
                    new SqlParameter("@goodsId",gid)
                };
                DataTable priceDt = ado.ExecuteSqlDataset(strSql, p2).Tables[0];
                if (priceDt.Rows.Count >= 2)
                {
                    return "您已经报价过两次，第二次的报价已作为您的最终报价";
                }

                if (priceDt.Rows.Count > 0)
                {
                    if (Common.NullToZero(priceDt.Rows[0]["IsEmployerSelect"]) == 1)
                        return "您的报价已被雇主选中，不可重新报价";
                }

                //add new
                strSql = @"select * from T_Goods_Info where goodsId=@goodsId";
                SqlParameter[] p4 = new SqlParameter[] {
                    new SqlParameter("@goodsId",gid)
                };
                DataTable gDt = ado.ExecuteSqlDataset(strSql, p4).Tables[0];
                
                //判断是否是雇主自己
                if (gDt.Rows[0]["ProviderInfo"].ToString().Equals(memberId))
                {
                    return "雇主无法给自己的任务进行报价";
                }
                
                string lastPriceId = Guid.NewGuid().ToString();
                strSql = @"insert into T_Goods_MemberPrice(PriceId,JobType,GoodsId,MemberId,MemberMobile,MemberPrice,CreateTime,IsLast,IsEmployerSelect,IsMemberConfirm,JobStartTime,JobEndTime,JobDay) values(@PriceId,@JobType,@GoodsId,@MemberId,@MemberMobile,@MemberPrice,@CreateTime,1,0,0,@JobStartTime,@JobEndTime,@JobDay);";
                SqlParameter[] p3 = new SqlParameter[] {
                        new SqlParameter("@PriceId",lastPriceId),
                        new SqlParameter("@JobType",jobType),
                        new SqlParameter("@GoodsId",gid),
                        new SqlParameter("@MemberId",memberId),
                        new SqlParameter("@MemberMobile",mobile),
                        new SqlParameter("@MemberPrice",price),
                        new SqlParameter("@CreateTime",DateTime.Now.ToString()),
                        new SqlParameter("@JobStartTime",gDt.Rows[0]["JobStartTime"]),
                        new SqlParameter("@JobEndTime",gDt.Rows[0]["JobEndTime"]),
                        new SqlParameter("@JobDay",gDt.Rows[0]["JobDay"]),
                    };
                if (ado.ExecuteSqlNonQuery(strSql, p3) > 0)
                {
                    //只保留一个最新的报价，其他报价IsLast重置为0
                    if (priceDt.Rows.Count > 0)
                    {
                        ado.ExecuteSqlNonQuery("update T_Goods_MemberPrice set IsLast=0 where MemberId='" + memberId + "' and GoodsId='" + gid + "' and PriceId<>'" + lastPriceId + "'");
                    }
                }

                string mId = Common.GetBossIdByGoodsId(gid);
                string GoodsName = Common.GetGoodsNameByGoodsId(gid);
                string TrueName = ado.ExecuteSqlScalar("select top 1 TrueName from T_Member_Info where MemberId='" + memberId + "'").ToString();

                Common.AddLogMsg(mId, "用户报价", "【" + GoodsName + "】任务已收到来自用户 " + TrueName + " 的报价", "MyTask" + (jobType == "DG" ? "People" : "") + "Info.html?gid=" + gid, 0);
                return "1";
            }
        }
        else
        {
            return "fill resume";
        }
    }

    private string AcceptOrder(string PriceId,string confirm)
    {
        if (!confirm.Equals("1"))
            confirm = "0";
        string strSql = @"update T_Goods_MemberPrice set IsMemberConfirm=@confirm,MemberConfirmTime=getdate() where memberid=@memberId and PriceId=@PriceId";
        SqlParameter[] p = new SqlParameter[] {
            new SqlParameter("@confirm",confirm),
            new SqlParameter("@PriceId",PriceId),
            new SqlParameter("@memberId",memberId)
        };
        string result=ado.ExecuteSqlNonQuery(strSql, p).ToString();
        if (confirm.Equals("1"))
        {
            string mId = Common.GetBossIdByPriceId(PriceId);
            string GoodsName = Common.GetGoodsNameByPriceId(PriceId);
            string TrueName = Common.GetWorkerNameByPriceId(PriceId);
            Common.AddLogMsg(mId, "雇员接受任务", "雇员 " + TrueName + " 已接受【" + GoodsName + "】任务","MyOrder.html",0);
        }

        return result;
    }

    private string Delete(string PriceId)
    {
        string strSql = @"delete from T_Goods_MemberPrice where memberid=@memberId and PriceId=@PriceId";
        SqlParameter[] p = new SqlParameter[] {
                        new SqlParameter("@PriceId",PriceId),
                        new SqlParameter("@memberId",memberId)
                    };

        string mId = Common.GetBossIdByPriceId(PriceId);
        string GoodsName = Common.GetGoodsNameByPriceId(PriceId);
        string TrueName = Common.GetWorkerNameByPriceId(PriceId);
        Common.AddLogMsg(mId, "雇员拒绝任务", "雇员 " + TrueName + " 已拒绝【" + GoodsName + "】任务","MyOrder.html",0);
        
        return ado.ExecuteSqlNonQuery(strSql, p).ToString();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}